﻿using System;
using System.Drawing;
using System.Net;
using System.Threading;
using System.Windows.Forms;
using System.Diagnostics;
namespace UpFile
{
    public partial class UploadFile : Form
    {
        #region 变量
        FTPClient ftp = null;
        FTPClient ftpup = null;
        string fileName;
        string fileFullName;
        string fileguid;
        string title;
        string projectremark;
        string strGIud;
        string strsuffix;
        string previewfullName;
        string previewName;
        string previewsuffix;
        string attributeStr;
        int userid;
        string username;
        int branchid;
        string NASIP;
        int flag;//判断该上传文件类型 0表示图片文件 1表示视频文件
        bool ishead;//判断是否是总店在进行上传操作
        string NASusername = System.Configuration.ConfigurationSettings.AppSettings["LocalUserName"];//NAS用户名
        string NASpassword = System.Configuration.ConfigurationSettings.AppSettings["LocalPassword"];//NAS密码
        string firstURL = System.Configuration.ConfigurationSettings.AppSettings["URL"];
        string ImageURL = System.Configuration.ConfigurationSettings.AppSettings["ImageURL"];//图片存储二级地址
        string VideoURL = System.Configuration.ConfigurationSettings.AppSettings["VideoURL"];//视频存储二级地址
        string HeadNASIP = System.Configuration.ConfigurationSettings.AppSettings["HeadNASIP"];//总店NAS服务器IP地址
        string HeadnasUserName = System.Configuration.ConfigurationSettings.AppSettings["HeadUserName"];//总店NAS用户名
        string HeadnasPassword = System.Configuration.ConfigurationSettings.AppSettings["HeadPassword"];//总店NAS密码
        #endregion

        #region 构造方法
        public UploadFile()
        {
            userid = 0;
            username = "";
            branchid = 0;
            NASIP = "";
            InitializeComponent();
            progressBar1.Maximum = 100;
            progressBar1.Visible = false;
        }
        public UploadFile(int user_id, string user_name, int branch_id, string NAS_IP, bool is_head)
        {
            userid = user_id;
            username = user_name;
            branchid = branch_id;
            NASIP = NAS_IP;
            ishead = is_head;
            InitializeComponent();
            this.label1.Visible = false;
            this.txtpreview.Visible = false;
            this.btnpreview.Text = "上传";
            this.btnUP.Visible = false;
            progressBar1.Maximum = 100;
            progressBar1.Visible = false;
        }
        #endregion

        #region 上传按钮
        private void btnFile_Click(object sender, EventArgs e)
        {

            OpenFileDialog openDialog = new OpenFileDialog();
            openDialog.Multiselect = false;
            if (openDialog.ShowDialog() == DialogResult.OK)
            {
                this.txtFile.Text = openDialog.FileName;
            }
        }
        /// <summary>
        /// 预览图上传 选择按钮事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnpreview_Click(object sender, EventArgs e)
        {
            if (this.btnpreview.Text == "选择")
            {
                OpenFileDialog openDialog = new OpenFileDialog();
                openDialog.Multiselect = false;
                if (openDialog.ShowDialog() == DialogResult.OK)
                {
                    this.txtpreview.Text = openDialog.FileName;
                }
            }
            if (this.btnpreview.Text == "上传")
            {
                btnUP_Click(sender, e);
            }
        }
        #endregion

        #region 文件上传
        private void btnUP_Click(object sender, EventArgs e)
        {
            //上传图片
            if (rdbimage.Checked == true)
            {
                flag = 0;
            }
            //上传视频
            if (rdbvideo.Checked == true)
            {
                flag = 1;
            }
            if (chb_zhanshi.Checked)
            {
                attributeStr += "1,";
            }
            if (chb_xuetang.Checked)
            {
                attributeStr += "2,";
            }
            if (chb_dingzhi.Checked)
            {
                attributeStr += "3,";
            }
            if (chb_hotel.Checked)
            {
                attributeStr += "4,";
            }
            if (chb_xilai.Checked)
            {
                attributeStr += "5,";
            }
            if (chb_hunli.Checked)
            {
                attributeStr += "6,";
            }
            fileFullName = this.txtFile.Text.Trim();//上传文件全路径
            title = this.txbtitle.Text.Trim();//主题
            projectremark = this.txb_project.Text.Trim();//文件项目备注
            fileName = fileFullName.Substring(fileFullName.LastIndexOf(@"\") + 1);//文件名
            strsuffix = fileName.Substring(fileName.LastIndexOf(".") + 1).ToLower();//文件后缀名
            progressBar1.Value = 0;
            progressBar1.Visible = true;
            ftp = new FTPClient(NASIP, "", NASusername, NASpassword, 21);//分店FTP
            ftpup = new FTPClient(HeadNASIP, "", HeadnasUserName, HeadnasPassword, 21);//总店FTP
            //判断可执行文件
            if (strsuffix == "exe" || strsuffix == "bat" || strsuffix == "sys" || strsuffix == "com")
            {
                MessageBox.Show("不能上传可执行文件", "提示信息", MessageBoxButtons.OK,
                                  MessageBoxIcon.Question,
                                  MessageBoxDefaultButton.Button1,
                                  0, true);
                return;
            }
            //判断是否选择文件
            if (string.IsNullOrEmpty(this.txtFile.Text.Trim()))
            {
                MessageBox.Show("请选择一个要上传的文件！", "系统提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                return;
            }
            //上传视频时要同时上传预览图片
            if (flag == 1)
            {
                previewfullName = this.txtpreview.Text.Trim();//预览图片全文件名
                previewName = previewfullName.Substring(previewfullName.LastIndexOf(@"\") + 1);//预览图片文件名
                previewsuffix = previewName.Substring(previewName.LastIndexOf(".") + 1).ToLower();//预览图片文件后缀名
                //判断是否选择预览图片
                if (string.IsNullOrEmpty(this.txtpreview.Text.Trim()))
                {
                    MessageBox.Show("请选择一个要上传的预览图片！", "系统提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    return;
                }
                //判断上传的是否为图片
                if (previewsuffix != "jpg" && previewsuffix != "bmp" && previewsuffix != "gif" && previewsuffix != "png")
                {
                    MessageBox.Show("请上传图片文件！", "系统提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    return;
                }
                //判断上传的是否为视频
                if (strsuffix != "flv" && strsuffix != "wmv" && strsuffix != "mp4" && strsuffix != "avi" && strsuffix != "rmvb" && strsuffix != "f4v" && strsuffix != "mov")
                {
                    MessageBox.Show("请上传视频文件！", "系统提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    return;
                }
            }
            //上传图片
            if (flag == 0)
            {
                if (strsuffix != "jpg" && strsuffix != "bmp" && strsuffix != "gif" && strsuffix != "png")
                {
                    MessageBox.Show("请上传图片！", "系统提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    return;
                }
            }
            //上传
            try
            {
                SynchronizationContext uiContext = SynchronizationContext.Current;
                Thread upThread = new Thread(upFile);
                upThread.Start(uiContext);
                if (upThread.ThreadState == System.Threading.ThreadState.Suspended)
                {
                    MessageBox.Show("文件上传成功！", "系统提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show("文件上传失败！", "系统提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
        }
        #endregion

        #region 文件上传进程方法
        private void upFile(object state)
        {
            strGIud = System.Guid.NewGuid().ToString();
            fileguid = strGIud + "." + strsuffix;
            if ((string.IsNullOrEmpty(this.txtFile.Text.Trim()) || (ftp.GetFileSize(fileName) != 0)))
            {
                return;
            }
            else
            {
                string strArry = ",jpg,bmp,gif,png,flv,wmv,mp4,avi,rmvb,f4v,mov";
                int intjudge = strArry.IndexOf("," + strsuffix + ",");
                ftp.ChDir(firstURL);
                ftpup.ChDir(firstURL);
                if (flag == 1)
                {
                    ftp.ChDir(VideoURL);
                    ftpup.ChDir(VideoURL);
                }
                else if (flag == 0)
                {
                    ftp.ChDir(ImageURL);
                    ftpup.ChDir(ImageURL);
                }
                ftpup.Put(fileFullName, fileguid, state, UpdateUI); //上传文件
                if (!ishead)
                {
                    ftp.Put(fileFullName, fileguid);
                }
                if (intjudge >= 0)
                {
                    if (!Thumbnail(state))
                    {
                        try
                        {
                            string uri = "ftp://" + NASIP + firstURL + ImageURL + fileguid;
                            FtpWebRequest reqFTP;
                            reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri(uri));
                            reqFTP.UseBinary = true;
                            if (ishead)
                            {
                                reqFTP.Credentials = new NetworkCredential(NASusername, NASpassword);
                            }
                            else
                            {
                                reqFTP.Credentials = new NetworkCredential(HeadnasUserName, HeadnasPassword);
                            }

                            reqFTP.Method = WebRequestMethods.Ftp.DeleteFile;
                            WebResponse response = reqFTP.GetResponse();
                            response.Close();
                        }
                        catch (Exception)
                        {
                            MessageBox.Show("文件上传失败后删除文件失败！", "系统提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                        }
                    }
                }
            }
        }
        #endregion

        #region 生成缩略图方法
        public bool Thumbnail(object state)
        {
            try
            {
                string pathImageFrom = "";
                if (flag == 1)
                {
                    pathImageFrom = previewfullName;
                }
                else if (flag == 0)
                {
                    pathImageFrom = fileFullName;
                }
                //生成缩略图
                if (GenThumbnail(pathImageFrom, state, 300, 170))
                {
                    return true;
                }
                else
                {
                    return false;
                }
            }
            catch
            {
                return false;
            }
        }
        #endregion

        #region 界面进度条更新
        /// <summary>
        /// This method is executed on the main UI thread.
        /// </summary>
        private void UpdateUI(object state)
        {
            if (state is decimal)
            {
                decimal text = Convert.ToDecimal(state);
                if (text > Convert.ToDecimal(1))
                {
                    text = 1;
                    progressBar1.Visible = false;
                }
                if (progressBar1.Value != progressBar1.Maximum)
                {
                    progressBar1.Visible = true;
                    progressBar1.Value = Convert.ToInt32(text * 100);
                    int l_value = 100 * (progressBar1.Value - progressBar1.Minimum) / (progressBar1.Maximum - progressBar1.Minimum);
                    labAvge.Text = Convert.ToInt32(l_value).ToString() + "%";
                }
            }
            else if (state is string)
            {
                this.lbltips.Text = state.ToString();
                progressBar1.Value = 0;
                labAvge.Text = "";
            }
            else
            {
                MessageBox.Show(state.ToString());
            }

        }
        #endregion

        #region 生成缩略图
        /// <summary>
        /// 生成缩略图
        /// </summary>
        /// <param name="originalImagePath">源图路径（物理路径）</param>
        /// <param name="thumbnailPath">缩略图路径（物理路径）</param>
        /// <param name="width">缩略图宽度</param>
        /// <param name="height">缩略图高度</param>
        /// <param name="mode">生成缩略图的方式</param> 
        public bool GenThumbnail(string pathImageFrom, object objState, int width, int height)
        {
            SynchronizationContext uiContext = objState as SynchronizationContext;
            uiContext.Post(UpdateUI, "正在生成缩略图！");
            Image imageFrom = null;
            try
            {
                imageFrom = Image.FromFile(pathImageFrom);
            }
            catch
            {
                MessageBox.Show("图片格式无效或图片不存在！", "系统提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                uiContext.Post(UpdateUI, " ");
                return false;
            }
            if (imageFrom == null)
            {
                return false;
            }
            // 源图宽度及高度 
            int imageFromWidth = imageFrom.Width;
            int imageFromHeight = imageFrom.Height;
            // 生成的缩略图实际宽度及高度 
            int bitmapWidth = width;
            int bitmapHeight = height;
            // 生成的缩略图在上述"画布"上的位置 
            int X = 0;
            int Y = 0;
            // 根据源图及欲生成的缩略图尺寸,计算缩略图的实际尺寸及其在"画布"上的位置 
            if (bitmapHeight * imageFromWidth > bitmapWidth * imageFromHeight)
            {
                //bitmapHeight = imageFromHeight * width / imageFromWidth;
                Y = (height - bitmapHeight) / 2;
            }
            else
            {
                //bitmapWidth = imageFromWidth * height / imageFromHeight;
                X = (width - bitmapWidth) / 2;
            }
            // 创建画布 
            Bitmap bmp = new Bitmap(width, height);
            Graphics g = Graphics.FromImage(bmp);
            // 用白色清空    
            g.Clear(Color.White);
            // 指定高质量的双三次插值法。执行预筛选以确保高质量的收缩。此模式可产生质量最高的转换图像。 
            g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.High;
            //// 指定高质量、低速度呈现。 
            g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;
            // 在指定位置并且按指定大小绘制指定的 Image 的指定部分。 
            g.DrawImage(imageFrom, new Rectangle(X, Y, bitmapWidth, bitmapHeight), new Rectangle(0, 0, imageFromWidth, imageFromHeight), GraphicsUnit.Pixel);
            try
            {
                byte[] bsThumbnailImage = ImageToStream(bmp);
                uiContext.Post(UpdateUI, "缩略图生成完成！");
                UploadFile upfile = new UploadFile(userid, username, branchid, NASIP, ishead);
                int USERID = upfile.userid;
                string USERNAME = upfile.username;
                int BRANCH_ID = upfile.branchid;
                string FILE_NAME = fileName;
                string URL = "";
                string PreFileName = "";
                if (previewfullName != null)
                {
                    PreFileName = previewfullName.Substring(previewfullName.LastIndexOf(@"\") + 1);
                }
                //byte[] bsPreviewImage = null;
                if (flag == 1)
                {
                    URL = firstURL + VideoURL;
                }
                else if (flag == 0)
                {
                    URL = firstURL + ImageURL;

                }
                uiContext.Post(UpdateUI, "缩略图上传中！");
                UpImage.UpFileSoapClient server = new UpImage.UpFileSoapClient();
                string newVideoImage = strGIud + "." + previewsuffix;
                string[] ParaStr = new string[] { strGIud, FILE_NAME, title, projectremark, flag.ToString(), USERID.ToString(), USERNAME, BRANCH_ID.ToString(), URL, newVideoImage, PreFileName, attributeStr };
                if (server.UpFileRsout(ParaStr, bsThumbnailImage))
                {
                    server.InsertFile(strGIud, BRANCH_ID, ishead);
                    uiContext.Post(UpdateUI, "缩略图上传成功！");
                    uiContext.Post(UpdateUI, " ");
                    return true;
                }
                else
                {
                    return false;
                }
            }
            catch (Exception ex)
            {
                uiContext.Post(UpdateUI, ex.Message.Substring(0, 4).ToString());
                return false;
            }
            finally
            {
                //显示释放资源 
                imageFrom.Dispose();
                bmp.Dispose();
                g.Dispose();
            }
        }

        public byte[] ImageToStream(Bitmap bmp)
        {
            System.IO.MemoryStream bstream = new System.IO.MemoryStream();
            bmp.Save(bstream, System.Drawing.Imaging.ImageFormat.Jpeg);
            bmp.Dispose();
            byte[] byteReturn = bstream.ToArray();
            bstream.Close();
            return byteReturn;
        }
        #endregion

        #region radiobutton选择显示
        private void rdbvideo_CheckedChanged(object sender, EventArgs e)
        {
            if (rdbvideo.Checked == true)
            {
                rdbimage.Checked = false;
                this.pnlpreview.Visible = true;
                this.label1.Visible = true;
                this.txtpreview.Visible = true;
                this.btnpreview.Text = "选择";
                this.btnUP.Visible = true;
                progressBar1.Visible = false;
            }
        }

        private void rdbimage_CheckedChanged(object sender, EventArgs e)
        {
            if (rdbimage.Checked == true)
            {
                rdbvideo.Checked = false;
                this.label1.Visible = false;
                this.txtpreview.Visible = false;
                this.btnpreview.Text = "上传";
                this.btnUP.Visible = false;
                progressBar1.Visible = false;
            }
        }

        private void btn_return_Click(object sender, EventArgs e)
        {
            FileManage form = new FileManage(userid, username, branchid, NASIP);//通过调用文件管理构造函数传值(用户信息)
            form.Show();
            this.Hide();
        }

        private void UploadFile_FormClosed(object sender, FormClosedEventArgs e)
        {
            System.Environment.Exit(0);
        }
    }
        #endregion
}
